package db;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.SimpleExpression;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * A data access object (DAO) providing persistence and search support for
 * Backreq entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see db.Backreq
 * @author MyEclipse Persistence Tools
 */

public class BackreqDAO extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(BackreqDAO.class);
	// property constants
	public static final String BACK_CODE = "backCode";
	public static final String TOB_ID = "tobId";
	public static final String BORREQ_ID = "borreqId";
	public static final String TEAM_ID = "teamId";
	public static final String PHASE = "phase";
	public static final String REQ_USER_ID = "reqUserId";
	public static final String MA_USER_ID = "maUserId";
	public static final String MA_STATE = "maState";
	public static final String ASS_USER_ID = "assUserId";
	public static final String ASS_STATE = "assState";
	public static final String OK_USER_ID = "okUserId";
	public static final String OK_STATE = "okState";

	protected void initDao() {
		// do nothing
	}

	public void save(Backreq transientInstance) {
		log.debug("saving Backreq instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(Backreq persistentInstance) {
		log.debug("deleting Backreq instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Backreq findById(java.lang.Integer id) {
		log.debug("getting Backreq instance with id: " + id);
		try {
			Backreq instance = (Backreq) getHibernateTemplate().get(
					"db.Backreq", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(Backreq instance) {
		log.debug("finding Backreq instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Backreq instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from Backreq as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByBackCode(Object backCode) {
		return findByProperty(BACK_CODE, backCode);
	}

	public List findByTobId(Object tobId) {
		return findByProperty(TOB_ID, tobId);
	}

	public List findByBorreqId(Object borreqId) {
		return findByProperty(BORREQ_ID, borreqId);
	}

	public List findByTeamId(Object teamId) {
		return findByProperty(TEAM_ID, teamId);
	}

	public List findByPhase(Object phase) {
		return findByProperty(PHASE, phase);
	}

	public List findByReqUserId(Object reqUserId) {
		return findByProperty(REQ_USER_ID, reqUserId);
	}

	public List findByMaUserId(Object maUserId) {
		return findByProperty(MA_USER_ID, maUserId);
	}

	public List findByMaState(Object maState) {
		return findByProperty(MA_STATE, maState);
	}

	public List findByAssUserId(Object assUserId) {
		return findByProperty(ASS_USER_ID, assUserId);
	}

	public List findByAssState(Object assState) {
		return findByProperty(ASS_STATE, assState);
	}

	public List findByOkUserId(Object okUserId) {
		return findByProperty(OK_USER_ID, okUserId);
	}

	public List findByOkState(Object okState) {
		return findByProperty(OK_STATE, okState);
	}

	public List findAll() {
		log.debug("finding all Backreq instances");
		try {
			String queryString = "from Backreq";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Backreq merge(Backreq detachedInstance) {
		log.debug("merging Backreq instance");
		try {
			Backreq result = (Backreq) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Backreq instance) {
		log.debug("attaching dirty Backreq instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Backreq instance) {
		log.debug("attaching clean Backreq instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static BackreqDAO getFromApplicationContext(ApplicationContext ctx) {
		return (BackreqDAO) ctx.getBean("BackreqDAO");
	}
	
	public Map getBackreq(int pageNo, int pageSize, String[][] order, List where, String[][] fields, String[] join) {
		ProjectionList pl = Projections.projectionList();	
		for (int i = 0; i < fields.length; i++) {
			String[] field = fields[i];
			if("group".equals(field[0])){
				pl.add(Projections.groupProperty(field[1]));
			}else{
				pl.add(Projections.property(field[1]));
			}
		}
		
		DetachedCriteria dc = DetachedCriteria.forClass(Backreq.class);
		if(join != null && join.length > 0)
			for(int i=0;i<join.length;i++){
				if("borreq".equals(join[i]))
					dc.createAlias("borreq", "o");
				else if("project".equals(join[i]))
					dc.createAlias("o.project", "op");
			}
		dc.setProjection(pl);

		if(order != null && order.length > 0)
		for(int i=0; i<order.length; i++){
			String[] temp = order[i];
			if ("desc".equals(order[i][0])) {
				dc.addOrder(Order.desc(order[i][1]));
			} else if ("asc".equals(order[i][1])) {
				dc.addOrder(Order.asc(order[i][1]));
			}
		}
		
		if(where != null && where.size() > 0)
		for(int i=0; i<where.size(); i++){
			Object[] w = (Object[])where.get(i);
			String condition = String.valueOf(w[0]);
			String filed = String.valueOf(w[1]);
			if("eq".equals(condition)){
				dc.add(Property.forName(filed).eq(w[2]));
			}else if("like".equals(condition)){
				dc.add(Property.forName(filed).like("%" + w[2] + "%"));
			}else if("ne".equals(condition)){
				dc.add(Property.forName(filed).ne(w[2]));
			}else if("or".equals(condition)){
				dc.add(handleOr((List)w[2]));
			}
		}
       
		int recordSize = getCount(where, join);
		
		List data = getHibernateTemplate().findByCriteria(dc,pageNo * pageSize, pageSize);
		
		int pageTotal = pageSize == 0 ? 1 : recordSize % pageSize == 0 ? recordSize / pageSize : recordSize / pageSize + 1;
		Map map = new HashMap();
		map.put("data", data);
		map.put("recordSize", recordSize);
		//System.out.println("============>>>>######>>>>"+pageTotal);
		map.put("pageTotal", pageTotal);
		map.put("pageSize", pageSize);
		map.put("pageNo", pageNo);
		return map;
	}
	
	public int getCount(List where, String[] join){
		DetachedCriteria dc = DetachedCriteria.forClass(Backreq.class)
		.setProjection(Projections.rowCount());
		
		if(join != null && join.length > 0)
			for(int i=0;i<join.length;i++){
				if("borreq".equals(join[i]))
					dc.createAlias("borreq", "o");
				else if("project".equals(join[i]))
					dc.createAlias("o.project", "op");
			}
		
		if(where != null && where.size() > 0)
		for(int i=0;i<where.size();i++){
			Object[] w = (Object[])where.get(i);
			String condition = String.valueOf(w[0]);
			String filed = String.valueOf(w[1]);
			if("eq".equals(condition)){
				dc.add(Property.forName(filed).eq(w[2]));
			}else if("like".equals(condition)){
				dc.add(Property.forName(filed).like("%" + w[2] + "%"));
			}else if("ne".equals(condition)){
				dc.add(Property.forName(filed).ne(w[2]));
			}else if("or".equals(condition)){
				dc.add(handleOr((List)w[2]));
			}
		}
		
		return (Integer) getHibernateTemplate().findByCriteria(dc).get(0);
	}
	
	public LogicalExpression handleOr(List list){
		LogicalExpression le = null;
		SimpleExpression se = null;
		SimpleExpression se1 = null;
		SimpleExpression se2 = null;
		
		for(int i= list.size() - 1;i >= 0;i--){
			Object[] where = (Object[])list.get(i);
			String condition = String.valueOf(where[0]);
			String filed = String.valueOf(where[1]);
			
			if("eq".equals(condition)){
				if(le == null){
					if(se1 == null)
						se1 = Restrictions.eq(filed, where[2]);
					else if(se2 == null)
						se2 = Restrictions.eq(filed, where[2]);
				}else{
					se = Restrictions.eq(filed, where[2]);
				}
			}else if("like".equals(condition)){
				if(le == null){
					if(se1 == null)
						se1 = Restrictions.like(filed, "%" + where[2] + "%");
					else if(se2 == null)
						se2 = Restrictions.like(filed, "%" + where[2] + "%");
				}else{
					se = Restrictions.like(filed, "%" + where[2] + "%");
				}
			}else if("ne".equals(condition)){
				if(le == null){
					if(se1 == null)
						se1 = Restrictions.ne(filed, where[2]);
					else if(se2 == null)
						se2 = Restrictions.ne(filed, where[2]);
				}else{
					se = Restrictions.ne(filed, where[2]);
				}
			}
			
			if(le == null){
				if(se1 != null && se2 != null){
					le = Restrictions.or(se1,se2);
				}
			}else{
				le = Restrictions.or(se,le);
			}
		}
		
		return le;
	}
}